package cn.achao.csr.chat.service.impl;

import cn.achao.csr.api.SequenceApi;
import cn.achao.csr.api.model.entity.ChatUser;
import cn.achao.csr.api.model.req.BatchUserInfoReq;
import cn.achao.csr.api.model.resp.UserInfoResp;
import cn.achao.csr.base.constant.ChatConstants;
import cn.achao.csr.base.constant.Constants;
import cn.achao.csr.base.constant.SecurityConstants;
import cn.achao.csr.base.utils.StringUtils;
import cn.achao.csr.chat.core.event.UserRegisterEvent;
import cn.achao.csr.chat.dao.ChatUserDao;
import cn.achao.csr.chat.service.ChatUserService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.achao.csr.base.constant.ChatConstants.CHAT_USER_PREFIX;

/**
 * (ChatUser)表服务实现类
 *
 * @author achao
 * @since 2025-02-10 19:37:23
 */
@Slf4j
@Service("chatUserService")
@RequiredArgsConstructor
public class ChatUserServiceImpl implements ChatUserService {

    private final SequenceApi sequenceApi;
    private final ChatUserDao userDao;
    private final ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void register(ChatUser user) {
        Long userId = sequenceApi.getSegmentId(user.sequenceCode(), SecurityConstants.INNER);
        userId = Long.valueOf("1" + userId);
        user.setId(userId);
        String userAccount = user.getUserAccount();
        if (StringUtils.isBlank(userAccount)) {
            Long segmentId = sequenceApi.getSegmentId("csr_user_account", SecurityConstants.INNER);
            userAccount = Constants.PROJECT_NAME + segmentId;
            user.setUserAccount(userAccount);
        }
        userDao.save(user);
        applicationEventPublisher.publishEvent(new UserRegisterEvent(this, user));
    }

    @Override
    public List<UserInfoResp> getSummeryUserInfo(BatchUserInfoReq req) {
        Set<Long> ids = req.getReqList().stream().map(infoReq -> infoReq.getUid()).collect(Collectors.toSet());
        if (ids.isEmpty()) {
            return Collections.emptyList();
        }
        List<ChatUser> chatUsers = userDao.listByIds(ids);
        return chatUsers.stream().map(chatUser -> {
            UserInfoResp resp = new UserInfoResp();
            resp.setUid(chatUser.getId());
            resp.setName(chatUser.getNickName());
            resp.setAvatar(chatUser.getAvatarUrl());
            return resp;
        }).collect(Collectors.toList());
    }

    /**
     * 用户上线，更新数据
     * @param userId
     */
    @Async
    @Override
    public void online(Long userId) {
        if (userId != null && ChatConstants.CHAT_USER_PREFIX.equals(userId.toString().substring(0, 1))) {
            userDao.online(userId);
        }
    }

    /**
     * 用户下线，更新数据
     * @param userId
     */
    @Async
    @Override
    public void offline(Long userId) {
        if (userId != null && ChatConstants.CHAT_USER_PREFIX.equals(userId.toString().substring(0, 1))) {
            userDao.offline(userId);
        }
    }
}
